package com.itshen.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 备注：多线程之间按顺序调用，实现A->B->C
 * 三个线程启动，要求如下：
 * <p>
 * A打印1，B打印2，C打印3
 * 接着
 * A打印1，B打印2，C打印3
 * 来10轮
 */
public class ConditionDemo {

    public static void main(String[] args) {
        PrintClass print = new PrintClass();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                print.printA();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                print.printB();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                print.printC();
            }
        }, "C").start();
    }
}

class PrintClass {
    // A:1, B:2, C:3
    private int number = 1;
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void printA() {
        lock.lock();
        try {
            // 1、判断
            while (number != 1) {
                // 等待
                c1.await();
            }
            // 2、干活
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            // 3、通知
            number = 2;
            c2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            // 1、判断
            while (number != 2) {
                // 等待
                c2.await();
            }
            // 2、干活
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            // 3、通知
            number = 3;
            c3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            // 1、判断
            while (number != 3) {
                // 等待
                c3.await();
            }
            // 2、干活
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            // 3、通知
            number = 1;
            c1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
